package leetcode.Top100;

import java.util.HashMap;
import java.util.Map;

/**
 * 3. 无重复字符的最长子串
 */
public class Top003_LC003 {
    public int lengthOfLongestSubstring(String s) {
        int len = s.length();
        if (len == 0) {
            return 0;
        }
        Map<Character, Integer> window = new HashMap<>();
        int left = 0, right = 0;
        int maxLen = 0;
        while(right < len) {
            char c1 = s.charAt(right);
            window.put(c1, window.getOrDefault(c1, 0) + 1);
            right++;
            while (window.get(c1) > 1) {
                char c2 = s.charAt(left);
                if (window.get(c2) < 1) {
                    window.remove(c2);
                } else {
                    window.put(c2, window.get(c2)-1);
                }
                left++;
            }
            if (right-left > maxLen) {
                maxLen = right-left;
            }
        }
        return maxLen;
    }
}
